package com.shopping_back.interceptor;

import com.shopping_back.annotation.Auth;
import com.shopping_back.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.thymeleaf.util.StringUtils;


public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        if(handler instanceof HandlerMethod) {
            final TokenUtil tokenUtil = new TokenUtil();
            final HandlerMethod handlerMethod = (HandlerMethod)handler;
            if ((handlerMethod.getBean() instanceof BasicErrorController)) {
                return true;
            }
            Auth auth = handlerMethod.getMethod().getAnnotation(Auth.class);
            if(auth != null&&auth.required()) {
                String token = request.getParameter("token");
                if(!StringUtils.isEmpty(token)){
                    //校验token
                    if (tokenUtil.verifyToken(token)) { // 校验 token 是否正确
                        return true;
                    } else {
                        request.getRequestDispatcher("/error/tokenError").forward(request, response);
                    }
                }else{
                    request.getRequestDispatcher("/error/tokenError").forward(request, response);
                }
            } else {
                return true;
            }
        }else{
            return true;
        }
        return false;
    }
}
